import React, { useEffect, useState, useRef } from 'react';
import './videoSide.less';
// import beforeStart from '../../imgs/beforeStart.jpg';
// import videoStart from '../../imgs/videoStart.jpg';
// import beforeBg from '../../imgs/beforeBg.png';
// import startBg from '../../imgs/startBg.png';
// import endBg from '../../imgs/endBg.png';
// import wechartCode from '../../imgs/code.jpg';
import axios from 'axios';
import { Modal } from 'antd';
// import {InfoCircleOutlined} from '@ant-design/icons';
declare var window: any
// declare var TDAPP: any

// const bgImg = 'http://img.iaquam.com/open/quiz_top-min.png';
// http://img.iaquam.com/open/mp-account-min.png 

const VideoSide = (props: any) => {

    const [times, setTimes] = useState(['0', '00', '00', '00']);
    const [visible, setVisible] = useState(false);
    const [videoImg, setVideoImg] = useState(true);
    const [activeSta, setActiveSta] = useState(0); //活动是否开始1：未开始，2：开始，3：结束
    //const [nowTimeStamp, setNowTimeStamp] = useState(0); //现在的时间
    // const [guanzhu, setGuanzhu] = useState(false);
    const videoSrc = [
        '',
        'http://img.iaquam.com/open/open-promo.mp4',
        'http://img.iaquam.com/open/open.mp4',
    ]
    const videoImgSrc = [
        '',
        'http://img.iaquam.com/open/beforeStart.jpg',
        'http://img.iaquam.com/open/videoStart.jpg',
    ]
    const bgImgSrc = [
        '',
        'http://img.iaquam.com/open/beforeBg.png',
        'http://img.iaquam.com/open/startBg.png',
        'http://img.iaquam.com/open/endBg.png'
    ]
    const intervalRef: any = useRef(null);

    // const endTimeStamp: any = new Date('2020-07-18 14:05:00').getTime(); //直播开始时间
    // const endActiveTimeStamp: any = new Date('2020-07-18 14:59:50').getTime(); //直播结束时间
    let nowTimeStamp: any = 0; //现在时间
    let endTimeStamp: any = 0; //直播开始时间
    let endActiveTimeStamp: any = 0; //直播结束时间

    function getTimeApi() {
        axios({
            method: 'get',
            url: '/status.php',
            headers:{
                'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            transformRequest: [function (data) {
                let ret = ''
                for (let it in data) {
                  ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                return ret
            }]
        }).then(function (response: any) {
            // eslint-disable-next-line
            if(response.status == 200) {
                // response.data = {
                //     "startTime": 1595056800,
                //     "endTime": 1595060000,
                //     "movieTime": 10800,
                //     "now": 1595056795,
                //     // "now": 1695056800,
                //     "isStart": 1,
                //     "startSurplusTime": 13259
                // }
                nowTimeStamp = response.data.now * 1000;
                endTimeStamp = response.data.startTime * 1000;
                endActiveTimeStamp = response.data.endTime * 1000;
                getTime();
            }
        })
    }

    const getTime = () => {
        let id = setInterval(() => {
            let hadTimeStamp: any = endTimeStamp - nowTimeStamp;
            nowTimeStamp = nowTimeStamp + 1000;
            if(hadTimeStamp > 0) {
                setActiveSta(1);
                let days: any = Math.floor(hadTimeStamp / (1000 * 60 * 60 * 24));
                let hours: any = Math.floor((hadTimeStamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                let minutes: any = Math.floor((hadTimeStamp % (1000 * 60 * 60)) / (1000 * 60));
                let seconds: any = Math.floor((hadTimeStamp % (1000 * 60)) / 1000);
                hours = hours < 10 ? '0' + hours : hours
                minutes = minutes < 10 ? '0' + minutes : minutes
                seconds = seconds < 10 ? '0' + seconds : seconds
                setTimes([days, hours, minutes, seconds])
            }else{
                if(nowTimeStamp > endActiveTimeStamp) {
                    setVideoImg(true);
                    setActiveSta(3);//直播结束
                }else{
                    // setVideoImg(true);
                    setActiveSta(2);//直播开始
                }
                clearTimeout(intervalRef.current);
            }
        }, 1000);
        intervalRef.current = id;
    }

    const playAudio = (play: boolean = false) => {
        let video: any = document.getElementById('movie');
        if (play && activeSta < 3) {
            setVideoImg(false);
            // if(activeSta === 2) {
            //     axios({
            //         method: 'get',
            //         url: '/status.php',
            //         headers:{
            //             'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            //         },
            //         transformRequest: [function (data) {
            //             let ret = ''
            //             for (let it in data) {
            //               ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            //             }
            //             return ret
            //         }]
            //     }).then(function (response: any) {
            //         // eslint-disable-next-line
            //         if(response.status == 200) {
            //             response.data = {
            //                 "startTime": 1595056800,
            //                 "endTime": 1595060000,
            //                 "movieTime": 10800,
            //                 "now": 1595056895,
            //                 // "now": 1695056800,
            //                 "isStart": 1,
            //                 "startSurplusTime": 13259
            //             }
            //             nowTimeStamp = response.data.now;
            //             endActiveTimeStamp = response.data.endTime;
            //             console.log(endActiveTimeStamp - nowTimeStamp)
            //             video.currentTime = endActiveTimeStamp - nowTimeStamp;
            //         }
            //     })
            // }
            if(activeSta === 2) {
                // window.TDAPP.onEvent('movieClick', '点击视频播放');
            }
            video.play();
        }else{
            setVideoImg(true);
            video.pause();
        }
    }

    function countDown() {
        setVisible(true);
        // window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdc9447e794080c04&redirect_uri=http%3A%2F%2Fopen.iaquam.com%2FvideoSidetext&response_type=code&scope=snsapi_base&state=STAT#wechat_redirect';
    }

    const handleCancel = () => {
        setVisible(false);
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdc9447e794080c04&redirect_uri=http%3A%2F%2Fopen.iaquam.com%2FvideoSide&response_type=code&scope=snsapi_base&state=STAT#wechat_redirect';
    }

    // 授权
    const getCode = () => {
        let searchStr = props.location.search;
        if(!searchStr) {
            window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdc9447e794080c04&redirect_uri=http%3A%2F%2Fopen.iaquam.com%2FvideoSide&response_type=code&scope=snsapi_base&state=STAT#wechat_redirect';
            return
        }
        let searchArr = searchStr.split('=');
        let code = searchArr[1].split('&')[0];
        axios({
            method: 'get',
            url: 'http://open-api.iaquam.com/merchant/user/login?code=' + code,
            headers:{
                'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            transformRequest: [function (data) {
                let ret = ''
                for (let it in data) {
                  ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                return ret
            }],
        }).then(function (response: any) {
            // console.log(response)
            // return
            //eslint-disable-next-line
            if (response.data.code != 0) {
                window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdc9447e794080c04&redirect_uri=http%3A%2F%2Fopen.iaquam.com%2FvideoSide&response_type=code&scope=snsapi_base&state=STAT#wechat_redirect';
                return
            }
            // eslint-disable-next-line
            if(response.data.code == 0 && response.data.data.subscribe == 0) {
                countDown()
            }else{
                // setGuanzhu(true)
                // countDown()
            }
        })
    }

    const endEd = () => {
        setActiveSta(3)
        setVideoImg(true);
    }

    useEffect(() => {
        getTimeApi();

        // let MapKv: any = {
        //     page_name: '观看视频页 - 穿越The Open 公开赛',
        // }
        // let scriptEle = document.createElement('script')
        // scriptEle.type = 'text/javascript'
        // scriptEle.src = "https://jic.talkingdata.com/app/h5/v1?appid=BE0B999FA8234987B29DE0F7B3AD8AF1&vn=LHR&vc=1.0.0";
        // document.head.appendChild(scriptEle)
        // scriptEle.onload = () => {
        //     window.TDAPP = TDAPP
        //     window.TDAPP.onEvent('index', '活动主页-穿越The Open 公开赛', MapKv);
        // }
        return ()=>clearTimeout(intervalRef.current);
        //eslint-disable-next-line
    }, []);

    useEffect(() => {
        if(activeSta === 2) {
            let elevideo: any = document.getElementById('movie');
            setVideoImg(true);
            elevideo.pause();
            //视频播放完成
            elevideo.addEventListener('ended', endEd, false)
            let timeDisplay: any;
            elevideo.addEventListener("timeupdate",function() {
                timeDisplay = elevideo.currentTime;
                // console.log(timeDisplay)
            },false)
            getCode();
            return () => {
                // window.TDAPP.onEvent('进度', '离开页面或播放完', {video_time: timeDisplay});
            }
        }
    //eslint-disable-next-line
    },[activeSta])

    return (
        <div className='warp'>
            <div className='vodeo-img-min'>
                <img src={bgImgSrc[activeSta]} width='100%' alt="" />
            </div>
            {
                activeSta < 1 ? <div className='vodeo-bg-min'></div> : null
            }
            {
                //结束
                activeSta > 2 ? <div className='video-end'>
                    <div className='video-endtitle'>请继续关注The R&A</div>
                    <div className='video-endtitle'>官方公众号</div>
                    <img src='http://img.iaquam.com/open/code.jpg' width='100%' alt="" />
                </div> : null
            }
            {
                activeSta === 1 ? <div className='video-time-box'>
                <div className='video-title'>目前距全球播放时间还有</div>
                <div className='video-times'>
                    {times[0]}<span className='video-type'>天 </span>
                    {times[1]}<span className='video-type'>小时 </span>
                    {times[2]}<span className='video-type'>分 </span>
                    {times[3]}<span className='video-type'>秒</span>
                </div>
            </div> : null
            }
            <div className='video-box'>
                {/* poster 下载时候显示的图片 */}
                <div hidden={videoImg}>
                    <video id="movie" onClick={() => playAudio(false)} x5-playsinline=""  webkit-playsinline="" src={(activeSta >= 1 && activeSta < 3) ? videoSrc[activeSta]: ''} x-webkit-airplay='allow' x5-video-player-type='h5' x5-video-orientation='portraint' x5-video-player-fullscreen=''></video>
                </div>
                {
                    videoImg && activeSta < 3 ? <div className='video-img' onClick={() => playAudio(true)}>
                        <img src={videoImgSrc[activeSta]} alt=""/>
                    </div> : null
                }
            </div>
            {
                activeSta < 3 ? <div className='voideo-toVode'>
                    <img src="http://img.iaquam.com/open/go-vote-min.png" width='100%' alt=""/>
                </div> : null
            }
            <div className='voted-content voted-copyright'>
                所有内容版权为 The R&A 和 The Open 拥有，不得抄录
            </div>
            <Modal
                visible={visible}
                centered
                closable={false}
                width='300px'
                maskClosable={true}
                onCancel={() => handleCancel()}
                footer={null}
                >
                <div>
                    <img src="http://img.iaquam.com/open/mp-account-min.png" width='100%' alt=""/>
                </div>
            </Modal>
        </div>
    );
}

export default VideoSide